<?php

namespace App\Http\Controllers\Api;

use App\Models\Api\GoodsStore;
use App\Models\Api\GoodsCategory;
use App\Models\Api\Store;
use App\Models\Api\StoreCart;
use App\Models\Api\StoreGoods;
use App\Models\Api\StoreGoodsRepertoryLog;
use Illuminate\Support\Facades\DB;

class GoodsController extends BaseController
{

    /**
     * 补货商品列表
     */
    public function goodsList()
    {
        $pamas = $this->requestArr;
        $type = $this->requestArr['type'];
        $pamas['store_id'] = $this->userArr['store_id'];
        if ($type == 1) {
            $list = GoodsStore::getListBySid($pamas);
        } elseif ($type == 2) {
            $list = StoreGoods::getRepertoryList($pamas);
        } elseif ($type == 3) {
            $list = GoodsStore::getListBySid($pamas, 1);
        }
        successMsg($list);
    }

    /**
     * 商品分类列表
     */
    public function goodsCateList()
    {
        $list = GoodsCategory::getAllList();
        successMsg($list);
    }

    /**
     * 商品库存列表
     */
    public function repertoryList()
    {
        $pamas = $this->requestArr;
        $pamas['store_id'] = $this->userArr['store_id'];
        $list = StoreGoods::getRepertoryList($pamas, $limit = 10);
        successMsg($list);
    }

    /**
     * 商品库存出库
     */
    public function repertoryOut()
    {
        $goods_id = $this->requestArr['goods_id'] ?: 0;
        $goods_num = $this->requestArr['goods_num'] ?: 0;
        $remark = $this->requestArr['remark'] ?: '';
        $store_id = $this->userArr['store_id'];
        if ($goods_id && $goods_num) {
            $goodsInfo = StoreGoods::getInfoByGId($goods_id, $store_id);
            if ($goodsInfo) {
                $info['store_id'] = $store_id;
                $info['order_id'] = 0;
                $info['goods_id'] = $goods_id;
                $info['goods_num'] = $goods_num;
                $info['goods_money'] = $goodsInfo['goods_price'];
                $info['type'] = 1;
                $info['remark'] = $remark;
                $info['created_at'] = time();
                $info['create_user'] = $this->userArr['user_name'];
                $re = StoreGoodsRepertoryLog::insert(array_filter($info));
                if ($re) {
                    // 商户减去库存
                    StoreGoods::where(['store_id' => $store_id, 'goods_id' => $goods_id])->decrement('goods_total_num', $goods_num);
                    StoreGoods::where(['store_id' => $store_id, 'goods_id' => $goods_id])->decrement('goods_sale_num', $goods_num);
                    successMsg();
                }
                errorMsg('出库失败');
            }
            errorMsg('商品不存在');
        }
        errorMsg();
    }

    /**
     * 商品库存变动历史列表
     */
    public function repertoryLogList()
    {
        $type = $this->requestArr['type'] ?: 0;
        $store_id = $this->userArr['store_id'];
        $list = StoreGoodsRepertoryLog::getList($store_id, $type);
        successMsg($list);
    }

    /**
     * 获取单品详情
     */
    public function getSingleGoodsInfo()
    {
        $storeId = $this->userArr['store_id'];
        $goodsId = $this->requestArr['goods_id'];
        $where = ['goods_id' => $goodsId, 'store_id' => $storeId];
        $info = GoodsStore::getInfo($where);
        if ($info) {
            $info['goods_img_list'] = json_decode($info['goods_img_list'], true);
            successMsg($info);
        } else {
            errorMsg("商品已下架");
        }
    }

    /**
     * 获取组合商品详情
     */
    public function getMultipleGoodsInfo()
    {
        $storeId = $this->userArr['store_id'];
        $goodsId = $this->requestArr['goods_id'];
        $where = ['goods_id' => $goodsId, 'store_id' => $storeId];
        $info = GoodsStore::getInfo($where);
        if ($info) {
            unset($info['goods_price']);
            unset($info['sale_price']);
            unset($info['buy_num']);
            unset($info['get_num']);
            $info['goods_group'] = json_decode($info['goods_group'], true);
            $info['goods_img_list'] = json_decode($info['goods_img_list'], true);
            $goodsIds = array_column($info['goods_group'], 'id');

            $goods = GoodsStore::from('goods_store as gs')
                ->where(['gs.store_id' => $storeId])
                ->whereIn('gs.goods_id', $goodsIds)
                ->select('g.id', 'g.goods_price', 'g.goods_name', 'goods_img', 'gs.sale_price')
                ->leftJoin('goods as g', 'g.id', '=', 'gs.goods_id')
                ->get()
                ->toArray();
            if (count($goods) < count($goodsIds)) {
                errorMsg("未获取到此组合商品中的单品代理权" . count($goods) . count($goodsIds));
            }

            foreach ($info['goods_group'] as $key => &$val) {
                foreach ($goods as $k => $v) {
                    if ($val['id'] == $v['id']) {
                        $val['goods_price'] = $v['goods_price'];
                        $val['goods_name'] = $v['goods_name'];
                        $val['goods_img'] = $v['goods_img'];
                        $val['sale_price'] = $v['sale_price'];
                    }
                }
            }
            successMsg($info);
        } else {
            errorMsg("商品已下架");
        }
    }

    /**
     * 单品加入购物车
     */
    public function singleGoodsAddCart()
    {
        $goodsId = $this->requestArr['goods_id'];
        $goodsNum = $this->requestArr['goods_num'];
        $storeId = $this->userArr['store_id'];

        # 参数验证
        if ($goodsId <= 0) {
            errorMsg("请选择商品");
        }
        if ($goodsNum <= 0) {
            errorMsg("请选择商品数量");
        }
        $where['goods_pid'] = 0;
        $where['type'] = 1;
        $where['is_give'] = 0;
        $where['goods_id'] = $goodsId;
        $where['store_id'] = $storeId;

        $info = StoreCart::where($where)->first();
        if ($info) {
            # 更新购物车数量
            $data = ['goods_num' => $info['goods_num'] + 1];
            $res = StoreCart::editCart($info['id'], $data);
        } else {
            # 添加购物车记录
            $where['goods_num'] = $goodsNum;
            $res = StoreCart::addCart($where);
        }
        if ($res) {
            successMsg();
        }
        errorMsg("加入购物车失败，请稍后重试");
    }

    /**
     * 组合商品加入购物车
     */
    public function multipleGoodsAddCart()
    {
        $goodsId = $this->requestArr['goods_id'];
        $buy = json_decode($this->requestArr['buy'], true);
        $give = json_decode($this->requestArr['give'], true);
        $storeId = $this->userArr['store_id'];

        # 参数验证
        if ($goodsId <= 0) {
            errorMsg("请选择商品");
        }
        if (!count($buy)) {
            errorMsg("请选择商品");
        }

        foreach ($buy as $key => $val) {
            if ($val['id'] <= 0 || $val['number'] <= 0) {
                unset($buy[$key]);
            }
        }
        $buy = array_values($buy);
        if (!count($buy)) {
            errorMsg("请选择商品");
        }
        $buyJson = json_encode($buy);
        foreach ($give as $k => $v) {
            if ($v['id'] <= 0 || $v['number'] <= 0) {
                unset($give[$k]);
            }
        }
        $give = array_values($give);

        DB::beginTransaction();
        try {
            $goodsNum = 0;
            foreach ($buy as $bb) {
                $goodsNum += $bb['number'];
            }
            foreach ($give as $gg) {
                $goodsNum += $gg['number'];
            }
            $info['goods_pid'] = 0;
            $info['goods_id'] = $goodsId;
            $info['type'] = 2;
            $info['is_give'] = 0;
            $info['store_id'] = $storeId;
//            $info['goods_num'] = $goodsNum;
            $info['goods_num'] = 1;  //购物车添加默认为一组
            $info['group_num'] = 1;  //购物车添加默认为一组
            $info['goods_group'] = $buyJson;
            $resId = StoreCart::addCart($info);

            $buyArr = array();
            foreach ($buy as $b) {
                $tmp = array();
                $tmp['goods_pid'] = $resId;
                $tmp['goods_id'] = $b['id'];
                $tmp['type'] = 2;
                $tmp['is_give'] = 0;
                $tmp['store_id'] = $storeId;
                $tmp['goods_num'] = $b['number'];
                $tmp['updated_at'] = time();
                $tmp['created_at'] = time();
                $buyArr[] = $tmp;
            }
            StoreCart::insert($buyArr);

            $giveArr = array();
            foreach ($give as $g) {
                $tmp = array();
                $tmp['goods_pid'] = $resId;
                $tmp['goods_id'] = $g['id'];
                $tmp['type'] = 2;
                $tmp['is_give'] = 1;
                $tmp['store_id'] = $storeId;
                $tmp['goods_num'] = $g['number'];
                $tmp['updated_at'] = time();
                $tmp['created_at'] = time();
                $giveArr[] = $tmp;
            }
            StoreCart::insert($giveArr);

            DB::commit();
            successMsg();
        } catch (\Exception $e) {
            DB::rollBack();
            errorMsg('加入购物车失败，请稍后重试');
        }
    }

    /**
     * 统计购物车商品数量
     */
    public function getCartCount()
    {
        $storeId = $this->userArr['store_id'];

        $count = StoreCart::where(['store_id' => $storeId, 'goods_pid' => 0])->sum('goods_num');

        successMsg(['count' => $count]);
    }
}